package com.supplychainapi.service.impl.supplier;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.joindata.inf.common.basic.exceptions.ServiceException;
import com.supplychainapi.common.enums.ExceptionMessage;
import com.supplychainapi.dao.prod.ScmTbtreebuildMapper;
import com.supplychainapi.dao.prod.ScmTbtreetypeMapper;
import com.supplychainapi.domain.BeforeData;
import com.supplychainapi.domain.LoginCache;
import com.supplychainapi.domain.SeqNoType;
import com.supplychainapi.domain.TbtreebuildDto;
import com.supplychainapi.domain.treeBuild.TreeBuildSelectItem;
import com.supplychainapi.domain.treeBuild.TreeBuildType;
import com.supplychainapi.model.*;
import com.supplychainapi.param.ColTitle;
import com.supplychainapi.param.ScmTbtreebuildParam;
import com.supplychainapi.proxy.ValidateHelper;
import com.supplychainapi.service.*;
import com.supplychainapi.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 供应商树结构
 *
 * @author:xiezhiwei
 * @email:xiezhiwei@niwodai.net
 * @date:2017-09-28
 */
@Service
public class ScmTbtreebuildServiceImpl implements IScmTbtreebuildService {


	private Logger logger = LogManager.getLogger(ScmTbtreebuildServiceImpl.class);

	@Autowired
	private ScmTbtreebuildMapper scmTbtreebuildMapper;

	@Autowired
	ScmTbtreetypeMapper tbtreetypeMapper;

	@Autowired
	IScmTbtreebuildTypeService typeService;

	@Autowired
	ITbfinderlistService tbfinderlistService;

	@Autowired
	TbSeqNoService seqNoService;


	@Autowired
	TbMaterialService materialService;

	@Autowired
	IScmTbsupplierService tbsupplierService;

	@Autowired
	IScmTbcustService tbcustService;


	Map<String, ScmTbtreebuild> tbtreebuildMap = Maps.newHashMap();

	@Override
	public List<ScmTbtreebuild> getScmTbtreebuildInfos(String fsShopGUID) throws ServiceException {
		logger.info("fsShopGUID= {}", fsShopGUID);
		return scmTbtreebuildMapper.getScmTbtreebuildInfos(fsShopGUID);
	}

	@Override
	public List<ScmTbtreebuild> getScmTbtreebuildAllInfo(String fsShopGUID, String fsTreeTypeId) throws ServiceException {
		logger.info("fsShopGUID= {},fsTreeTypeId={}", fsShopGUID, fsTreeTypeId);
		List<ScmTbtreebuild> scmTbtreebuildList = scmTbtreebuildMapper.getScmTbtreebuildAllInfo(fsShopGUID, fsTreeTypeId);
		List<ScmTbtreebuild> resultTreeBuild = TreeUtils.buildByScmTbtreebuild(scmTbtreebuildList);
		return resultTreeBuild;
	}

	@Override
	public List<ScmTbtreebuild> getScmTbtreebuildAllInfos(String fsShopGUID, String fsTreeTypeId, String fdParentNodeCode) throws ServiceException {
		logger.info("fsShopGUID= {},fsTreeTypeId={}", fsShopGUID, fsTreeTypeId);
		if (StringUtils.isBlank(fdParentNodeCode)) {
			fdParentNodeCode = "0";
		}
		List<ScmTbtreebuild> scmTbtreebuildList = scmTbtreebuildMapper.getScmTbtreebuildAllInfo(fsShopGUID, fsTreeTypeId);
		List<ScmTbtreebuild> resultTreeBuild = TreeUtils.buildByScmTbtreebuild(scmTbtreebuildList);
		if (fdParentNodeCode.equals("0")) {
			return resultTreeBuild;
		}
		String finalFdParentNodeCode = fdParentNodeCode;

		List<ScmTbtreebuild> tbtreebuilds = Lists.newArrayList();
		resultTreeBuild.stream().forEach(e -> {
			if (e.getFdParentNodeCode().equals(finalFdParentNodeCode)) {
				tbtreebuilds.add(e);
			}
			if (null != e.getScmTbtreebuildList()) {
				e.getScmTbtreebuildList().stream().forEach(k -> {
					if (k.getFdParentNodeCode().equals(finalFdParentNodeCode)) {
						tbtreebuilds.add(k);
					}
					if (null != k.getScmTbtreebuildList()) {
						k.getScmTbtreebuildList().stream().forEach(l -> {
							if (l.getFdParentNodeCode().equals(finalFdParentNodeCode)) {
								tbtreebuilds.add(l);
							}
						});
					}
				});
			}
		});
//		resultTreeBuild.stream().filter(e->e.getFdParentNodeCode().equals(finalFdParentNodeCode)).collect(Collectors.toList());
		SortUtil.treeBuildsortByfiSort(tbtreebuilds);
		return tbtreebuilds;
	}

	@Override
	public List<ScmTbtreebuild> getScmTbtreebuildByFsNodeTextAllInfo(String fsShopGUID, String fsTreeTypeId, String fsNodeText) throws ServiceException {
		logger.info("fsShopGUID= {},fsTreeTypeId={},fsNodeText={}", fsShopGUID, fsTreeTypeId, fsNodeText);
		List<ScmTbtreebuild> scmTbtreebuildList = scmTbtreebuildMapper.getScmTbtreebuildByFsNodeTextAllInfo(fsShopGUID, fsTreeTypeId, fsNodeText);
		List<ScmTbtreebuild> resultTreeBuild = TreeUtils.buildByScmTbtreebuild(scmTbtreebuildList);
		return resultTreeBuild;
	}

	@Override
	public List<ScmTbtreebuild> getScmTbtreebuildAssembleInfo(String fsShopGUID, String fsTreeTypeId) throws ServiceException {
		logger.info("fsShopGUID= {}", fsShopGUID);
		List<ScmTbtreebuild> scmTbtreebuildList = scmTbtreebuildMapper.getScmTbtreebuildAllInfo(fsShopGUID, fsTreeTypeId);
		return scmTbtreebuildList;
	}

	@Override
	public boolean saveTreeBuild(ScmTbtreebuildParam param) throws ServiceException {
		ValidateHelper.validate(param);
		if (StringUtil.checkIsEmoji(param.getFsNodeText())) {
			throw ExceptionMessage.emoji_failed.getServiceException();
		}
		Integer k = scmTbtreebuildMapper.nameIsExit(param.getFsNodeText(), param.getFsShopGUID(), param.getFsTreeTypeId());
		if (k > 0) {
			throw ExceptionMessage.material_name_is_exit.getServiceException();
		}
		ScmTbtreebuild bean = new ScmTbtreebuild();
		BeanUtils.copyProperties(param, bean);
		bean.setFsCreateTime(new Date());
		String code = param.getFsNodeCode();
		bean.setFsUpdateTime(new Date());
		bean.setFsNodeCode(code);
		ScmTbtreetype tbtreetype = new ScmTbtreetype();
		tbtreetype.setFsTreeTypeId(bean.getFsTreeTypeId());
		tbtreetype.setFsShopGUID(bean.getFsShopGUID());
		ScmTbtreetype scmTbtreetype = tbtreetypeMapper.selectOne(tbtreetype);
		if (StringUtils.isNotBlank(bean.getFdParentNodeCode()) && !"0".equals(bean.getFdParentNodeCode())) {
			ScmTbtreebuild find = new ScmTbtreebuild();
			find.setFsNodeCode(bean.getFdParentNodeCode());
			find.setFsTreeTypeId(bean.getFsTreeTypeId());
			find.setFsShopGUID(bean.getFsShopGUID());
			ScmTbtreebuild result=scmTbtreebuildMapper.selectByPrimaryKey(find);
			if (null != result) {
				bean.setFdNodeLevel((short) (result.getFdNodeLevel() + 1));
				bean.setFsNodeFullText(result.getFsNodeFullText().concat("_").concat(bean.getFsNodeText()));
			}
		}else{
			bean.setFsNodeFullText(bean.getFsNodeText());
			bean.setFdNodeLevel((short) 1);
		}
		if (null != scmTbtreetype) {
			if (scmTbtreetype.getFiClassLvl() < bean.getFdNodeLevel()) {
				throw ExceptionMessage.tree_type_lv_error.getServiceException();
			}
		}
		ScmTbseqno tbseqno = new ScmTbseqno();
		tbseqno.setFsShopGUID(param.getFsShopGUID());
		tbseqno.setFsCls(check(param));
		tbseqno.setFiSeqNo(code);
		seqNoService.checkCode(code, conversion(param), param.getFsShopGUID());
		if (!RegexUtils.AutoCode(bean.getFsNodeCode())) {
			throw ExceptionMessage.auto_code_format.getServiceException();
		}
		int i = scmTbtreebuildMapper.insertSelective(bean);

		seqNoService.insert(tbseqno, tbseqno.getFsShopGUID());
		return i > 0;
	}

	private String check(ScmTbtreebuildParam param) {
		if (TreeBuildType.Cust.name().equals(param.getFsTreeTypeId())) {
//            param.setFsTreeTypeId(TreeBuildType.Cust.name());
			return TreeBuildType.Cust_Class.name();
		}
		if (TreeBuildType.Supplier.name().equals(param.getFsTreeTypeId())) {
//            param.setFsTreeTypeId(TreeBuildType.Supplier.name());
			return TreeBuildType.Supplier_Class.name();
		}
		if (TreeBuildType.Material.name().equals(param.getFsTreeTypeId())) {
//            param.setFsTreeTypeId(TreeBuildType.Material.name());
			return TreeBuildType.Material_Class.name();
		}
		return "";
	}

	private Integer conversion(ScmTbtreebuildParam param) {
		if (TreeBuildType.Cust.name().equals(param.getFsTreeTypeId())) {

			return SeqNoType.SEQNO_TREE_CUST.getCode();
		}
		if (TreeBuildType.Supplier.name().equals(param.getFsTreeTypeId())) {

			return SeqNoType.SEQNO_TREE_SUPPLIER.getCode();
		}
		if (TreeBuildType.Material.name().equals(param.getFsTreeTypeId())) {

			return SeqNoType.SEQNO_TREE_MATERIAL.getCode();
		}
		return 0;
	}


	@Override
	public boolean updateTreeBuild(ScmTbtreebuildParam param) throws ServiceException {
		ValidateHelper.validate(param);
		if (StringUtil.checkIsEmoji(param.getFsNodeText())) {
			throw ExceptionMessage.emoji_failed.getServiceException();
		}
		Integer k = scmTbtreebuildMapper.nameIsExit(param.getFsNodeText(), param.getFsShopGUID(), param.getFsTreeTypeId());
		if (k > 1) {
			throw ExceptionMessage.material_name_is_exit.getServiceException();
		}


		if (null != param.getFiStatus() && param.getFiStatus() == 9) {

			int b = getChildByTreeBuild(param.getFsShopGUID(), param.getFsNodeCode(), param.getFsTreeTypeId());
			if (b > 0) {
				throw ExceptionMessage.delete_failed.getServiceException();
			}
		}
		ScmTbtreebuild bean = new ScmTbtreebuild();
		BeanUtils.copyProperties(param, bean);
		bean.setFsUpdateTime(new Date());
		ScmTbtreetype tbtreetype = new ScmTbtreetype();
		tbtreetype.setFsTreeTypeId(bean.getFsTreeTypeId());
		tbtreetype.setFsShopGUID(bean.getFsShopGUID());
		ScmTbtreetype scmTbtreetype = tbtreetypeMapper.selectOne(tbtreetype);
		if (null != scmTbtreetype) {
			if (null != bean.getFdNodeLevel()) {
				if (scmTbtreetype.getFiClassLvl() < bean.getFdNodeLevel()) {
					throw ExceptionMessage.tree_type_lv_error.getServiceException();
				}
			}
		}
		ScmTbtreebuild findDb = scmTbtreebuildMapper.selectByPrimaryKey(bean);
		if (null != findDb && !findDb.getFsNodeText().equals(bean.getFsNodeText())) {// 名字和数据库不一样 说明改了名字     相关联的上下级  一起改名
			bean.setFsNodeFullCode(findDb.getFsNodeFullCode());
			updateFullText(bean);
		}
		bean.setFsNodeFullText(null);
		int i = scmTbtreebuildMapper.updateByPrimaryKeySelective(bean);
		return i > 0;
	}


	private void updateFullText(ScmTbtreebuild bean) throws ServiceException {
		updateTreeFullText(bean);
		switch (bean.getFsTreeTypeId()) {
			case Constants.SUPPLIER_CLASS:
				updateSupplierFullText(bean);
				break;
			case Constants.MATERIAL_CLASS:
				updateMaterialFullText(bean);
				break;
			case Constants.CUST_CLASS:
				updateCustFullText(bean);
				break;
		}
	}

	private void updateCustFullText(ScmTbtreebuild bean) throws ServiceException {
//		Map<String, ScmTbtreebuild> tbtreebuildMap = getAllByTypeAndShopGuidToMap(bean.getFsShopGUID(), bean.getFsTreeTypeId());
		List<ScmTbcust> list = tbcustService.findFullCode(bean.getFsShopGUID(), bean.getFsNodeCode());
		list.stream().forEach(e -> {
			StringBuffer buffer = new StringBuffer();
			if (StringUtils.isNotBlank(e.getFsNodeFullCode())) {//  全名code  拆成数组  从map中直接取分类名字拼接 update至库中
				String fullText = AssembleFullText(e.getFsNodeFullCode(), tbtreebuildMap);
				ScmTbcust tbcust = new ScmTbcust();
				tbcust.setFsCustId(e.getFsCustId());
				tbcust.setFsShopGUID(e.getFsShopGUID());
				tbcust.setFsNodeFullText(fullText);
				tbcust.setFsCustName(e.getFsCustName());
				tbcustService.updateFullText(tbcust);
			}
		});
	}

	private void updateSupplierFullText(ScmTbtreebuild bean) throws ServiceException {
//		Map<String, ScmTbtreebuild> tbtreebuildMap = getAllByTypeAndShopGuidToMap(bean.getFsShopGUID(), bean.getFsTreeTypeId());
		List<ScmTbsupplier> list = tbsupplierService.findFullCode(bean.getFsShopGUID(), bean.getFsNodeCode());
		list.stream().forEach(e -> {
			StringBuffer buffer = new StringBuffer();
			if (StringUtils.isNotBlank(e.getFsNodeFullCode())) {//  全名code  拆成数组  从map中直接取分类名字拼接 update至库中
				String fullText = AssembleFullText(e.getFsNodeFullCode(), tbtreebuildMap);
				ScmTbsupplier tbsupplier = new ScmTbsupplier();
				tbsupplier.setFsNodeFullText(fullText);
				tbsupplier.setFsShopGUID(e.getFsShopGUID());
				tbsupplier.setFsSupplierId(e.getFsSupplierId());
				tbsupplier.setFsSupplierName(e.getFsSupplierName());
				tbsupplierService.updateFullText(tbsupplier);
			}
		});
	}

	private void updateMaterialFullText(ScmTbtreebuild bean) throws ServiceException {
//		Map<String, ScmTbtreebuild> tbtreebuildMap = getAllByTypeAndShopGuidToMap(bean.getFsShopGUID(), bean.getFsTreeTypeId());
		List<ScmTbmaterial> tbmaterialList = materialService.findFullCode(bean.getFsShopGUID(), bean.getFsNodeCode());
		tbmaterialList.stream().forEach(e -> {
			StringBuffer buffer = new StringBuffer();
			if (StringUtils.isNotBlank(e.getFsNodeFullCode())) {//  全名code  拆成数组  从map中直接取分类名字拼接 update至库中
				String fullText = AssembleFullText(e.getFsNodeFullCode(), tbtreebuildMap);
				ScmTbmaterial model = new ScmTbmaterial();
				model.setFsMaterialId(e.getFsMaterialId());
				model.setFsShopGUID(e.getFsShopGUID());
				model.setFsNodeFullText(fullText);
				model.setFsMaterialName(e.getFsMaterialName());
				materialService.updateFullTextName(model);
			}
		});
	}

	private void updateTreeFullText(ScmTbtreebuild bean) throws ServiceException {
		tbtreebuildMap = getAllByTypeAndShopGuidToMap(bean.getFsShopGUID(), bean.getFsTreeTypeId());
		List<ScmTbtreebuild> tbtreebuildList = findFullCode(bean.getFsShopGUID(), bean.getFsNodeCode(), bean.getFsTreeTypeId());
		if (StringUtils.isNotBlank(bean.getFsNodeFullCode())) {
			String fullText = AssembleFullText(bean.getFsNodeFullCode(), tbtreebuildMap);
			Example example = new Example(ScmTbtreebuild.class);
			example.createCriteria().andEqualTo("fsNodeCode", bean.getFsNodeCode()).andEqualTo("fsShopGUID", bean.getFsShopGUID()).andEqualTo("fsTreeTypeId", bean.getFsTreeTypeId());
			ScmTbtreebuild tbtreebuil = new ScmTbtreebuild();
			tbtreebuil.setFsNodeFullText(fullText);
			ScmTbtreebuild tbtreebuild = tbtreebuildMap.get(bean.getFsNodeCode());
			if (null != tbtreebuild) {
				tbtreebuild.setFsNodeText(bean.getFsNodeText());
				tbtreebuildMap.put(tbtreebuild.getFsNodeCode(), tbtreebuild);
			}
			scmTbtreebuildMapper.updateByExampleSelective(tbtreebuil, example);
		}
		tbtreebuildList.stream().forEach(e -> {
			if (StringUtils.isNotBlank(e.getFsNodeFullCode())) {
				String fullText = AssembleFullText(e.getFsNodeFullCode(), tbtreebuildMap);
				Example example = new Example(ScmTbtreebuild.class);
				example.createCriteria().andEqualTo("fsNodeCode", e.getFsNodeCode()).andEqualTo("fsShopGUID", e.getFsShopGUID()).andEqualTo("fsTreeTypeId", e.getFsTreeTypeId());
				ScmTbtreebuild tbtreebuil = new ScmTbtreebuild();
				tbtreebuil.setFsNodeFullText(fullText);
				scmTbtreebuildMapper.updateByExampleSelective(tbtreebuil, example);
			}
		});

	}

	private String AssembleFullText(String fullCode, Map<String, ScmTbtreebuild> tbtreebuildMap) {
		StringBuffer buffer = new StringBuffer();
		String[] sz = {};
		if (StringUtils.isBlank(fullCode))
			return "";
		if (fullCode.contains("|")) {
			sz = fullCode.split("\\|");
		} else {
			sz = new String[]{fullCode};
		}
		for (String s : sz) {
			if (StringUtils.isNotBlank(s)) {
				ScmTbtreebuild tbtreebuild = tbtreebuildMap.get(s);
				if (null != tbtreebuild) {
					buffer.append(tbtreebuild.getFsNodeText().concat("_"));
				}
			}
		}
		String str = buffer.toString();
		if (str.contains("_")) {
			return str.substring(0, str.lastIndexOf("_"));
		} else {
			return str;
		}
	}


	//	private void build(Treebuild treebuild) {
//		switch (treebuild.getFsTreeTypeId()) {
//			case Constants.SUPPLIER_CLASS:
//				treebuild.setTable("scm_tbsupplier");
//				break;
//			case Constants.CUST_CLASS:
//				treebuild.setTable("scm_tbcust");
//				break;
//			case Constants.MATERIAL_CLASS:
//				treebuild.setTable("scm_tbmaterial");
//				break;
//			default:
//				break;
//		}
//	}
	@Override
	public boolean deleteTreeBuild(ScmTbtreebuildParam param) throws ServiceException {
		ScmTbtreebuild bean = new ScmTbtreebuild();
		BeanUtils.copyProperties(param, bean);
		int a = getQuotesByTreeBuild(bean.getFsTreeTypeId(), bean.getFsShopGUID(), bean.getFsNodeCode());
		if (a > 0) {
			throw ExceptionMessage.delete_treebuild_failed.getServiceException();
		}

		if (!"1".equals(bean.getFsNodeCode()) && !"2".equals(bean.getFsNodeCode()) && !"3".equals(bean.getFsNodeCode())) {
			int b = getChildByTreeBuild(bean.getFsShopGUID(), bean.getFsNodeCode(), bean.getFsTreeTypeId());
			if (b > 0) {
				throw ExceptionMessage.delete_failed.getServiceException();
			}

		}
		int i = scmTbtreebuildMapper.delete(bean);

		return i > 0;
	}

	@Override
	public ScmTbtreebuild selectByKey(ScmTbtreebuildParam model) throws ServiceException {
		ScmTbtreebuild tbtreebuild = new ScmTbtreebuild();
		BeanUtils.copyProperties(model, tbtreebuild);
		return scmTbtreebuildMapper.selectByPrimaryKey(tbtreebuild);
	}


	@Override
	public List<ScmTbtreebuild> getScmTbtreebuildOneLevelInfos(String fsShopGUID, Integer page, Integer pageSize, String fsTreeTypeId)
			throws ServiceException {
		logger.info("fsShopGUID= {},fsTreeTypeId={}", fsShopGUID, fsTreeTypeId);
		List<ScmTbtreebuild> scmTbtreebuildList = scmTbtreebuildMapper.getScmTbtreebuildOneLevelInfos(fsShopGUID, page, pageSize, fsTreeTypeId);
		return scmTbtreebuildList;
	}

	@Override
	public int getQuotesByTreeBuild(String fsTreeTypeId, String fsShopGUID, String fsNodeCode) {
		return scmTbtreebuildMapper.getQuotesByTreeBuild(fsTreeTypeId, fsShopGUID, fsNodeCode);

	}

	@Override
	public int getChildByTreeBuild(String fsShopGUID, String fdParentNodeCode, String fsTreeTypeId) {
		return scmTbtreebuildMapper.getChildByTreeBuild(fsShopGUID, fdParentNodeCode, fsTreeTypeId);

	}

	@Override
	public PageInfo getClassListInfo(String fsShopGUID, String fsNodeText, String fsTreeTypeId, Integer pageNum,
									 Integer pageSize) throws ServiceException {
		PageHelper.startPage(pageNum, pageSize);
		PageHelper.orderBy("fsNodeCode ASC");
		List<ScmTbtreebuild> classList = scmTbtreebuildMapper.getClassListInfo(fsShopGUID, fsNodeText, fsTreeTypeId);
		return new PageInfo(classList);
	}

	@Override
	public List<ColTitle> getSchema() {
		List<ColTitle> list = new ArrayList<ColTitle>();
		list.add(new ColTitle("fsNodeCode", "分类编号", "center", 100));
		list.add(new ColTitle("fsNodeText", "分类名称", "center", 100));
		list.add(new ColTitle("fsNodeFullText", "分类全名", "center", 100));
		list.add(new ColTitle("statusName", "状态", "center", 100));
		list.add(new ColTitle("__EDIT__", "操作", null, 150, "fsNodeCode"));
		return list;
	}

	@Override
	public List<TreeBuildSelectItem> getTree(String fsShopGUID, String fsTreeTypeId) throws ServiceException {
		return createTreeSelect(getScmTbtreebuildAllInfo(fsShopGUID, fsTreeTypeId));
	}

	private List<TreeBuildSelectItem> createTreeSelect(List<ScmTbtreebuild> builds) {
		if (builds == null || builds.isEmpty()) {
			return Collections.emptyList();
		}
		return builds.stream().map(b -> new TreeBuildSelectItem()
				.setLabel(b.getFsNodeText())
				.setValue(b.getFsNodeCode())
				.setFullName(b.getFsNodeFullText())
				.setLevel(b.getFdNodeLevel())
				.setChildren(createTreeSelect(b.getScmTbtreebuildList()))).collect(Collectors.toList());
	}


	@Override
	public PageInfo getScmTbtreebuildAllInfo(String fsShopGUID, String fsTreeTypeId, Integer pageNum, Integer pageSize) throws ServiceException {
		PageHelper.startPage(pageNum, pageSize);
		List<ScmTbtreebuild> scmTbtreebuildList = scmTbtreebuildMapper.getScmTbtreebuildAllInfo(fsShopGUID, fsTreeTypeId);
//		List<ScmTbtreebuild> resultTreeBuild = TreeUtils.buildByScmTbtreebuild(scmTbtreebuildList);
		List<TbtreebuildDto> list = Lists.newArrayList();
		scmTbtreebuildList.stream().forEach(e -> {
			TbtreebuildDto dto = new TbtreebuildDto();
			BeanUtils.copyProperties(e, dto);
			if (e.getFiStatus() == 1) {
				dto.setStatusName("正常");
			}
			if (e.getFiStatus() == 9) {
				dto.setStatusName("禁用");
			}
			list.add(dto);
		});
		PageInfo pageInfo = new PageInfo<ScmTbtreebuild>(scmTbtreebuildList);
		pageInfo.setList(list);
		return pageInfo;

	}

	@Override
	public boolean initLevel(Integer level, TreeBuildType treeBuildType, LoginCache loginCache) throws ServiceException {
		ScmTbtreetype model = new ScmTbtreetype();
		model.setFiClassLvl(Short.valueOf(String.valueOf(level)));
		model.setFsTreeTypeId(treeBuildType.name());
		model.setFsTreeTypeName(treeBuildType.name());
		model.setFsUpdateTime(new Date());
		model.setFsShopGUID(loginCache.getFsShopGUID());
		model.setFsUpdateUserId(loginCache.getFsUserId());
		model.setFsUpdateUserName(loginCache.getFsUserName());
		ScmTbtreebuildParam param = new ScmTbtreebuildParam();
		param.setFiStatus((short) 1);
		param.setFsShopGUID(loginCache.getFsShopGUID());
		param.setFsTreeTypeId(treeBuildType.name());
		param.setFiDataKind((short) 1);
		param.setFsNodeText("未分类");
		param.setFdNodeLevel((short) 1);
		param.setFsNodeFullText("未分类");
		param.setFsNodeCode("1");
		param.setFdParentNodeCode("0");
		param.setFsNodeFullCode("1");
		param.setFsCreateUserName(loginCache.getFsUserName());
		param.setFsCreateTime(new Date());
		param.setFsCreateUserId(loginCache.getFsUserId());
		for (int i = 1; i <= level; i++) {
			param.setFsNodeCode(i + "");
			deleteTreeBuild(param);
			if (i == 1) {
				saveTreeBuild(param);
			}
			if (i == 2) {
				ScmTbtreebuildParam two = new ScmTbtreebuildParam();
				BeanUtils.copyProperties(param, two);
				two.setFsNodeFullText("未分类_未分类.");
				two.setFdNodeLevel((short) 2);
				param.setFsNodeText("未分类.");
				param.setFdNodeLevel((short) 2);
				param.setFsNodeCode("2");
				param.setFdParentNodeCode("1");
				param.setFsNodeFullCode("1|2");
				saveTreeBuild(param);
			}
			if (i == 3) {
				ScmTbtreebuildParam two = new ScmTbtreebuildParam();
				BeanUtils.copyProperties(param, two);
				two.setFsNodeFullText("未分类_未分类._未分类..");
				two.setFdNodeLevel((short) 3);
				param.setFsNodeText("未分类..");
				param.setFdNodeLevel((short) 3);
				param.setFsNodeCode("3");
				param.setFdParentNodeCode("2");
				param.setFsNodeFullCode("1|2|3");
				saveTreeBuild(param);
			}
		}
		return typeService.update(model);
	}

	@Override
	public void sort(List<String> trees, String shopGuid, TreeBuildType treeBuildType) throws ServiceException {
		for (int i = 0; i < trees.size(); i++) {
			String code = trees.get(i);
			ScmTbtreebuildParam param = new ScmTbtreebuildParam();
			param.setFsShopGUID(shopGuid);
			param.setFsNodeCode(code);
			param.setFsTreeTypeId(treeBuildType.name());
			param.setFiSort(Short.valueOf(String.valueOf(i)));
			updateTreeBuild(param);
		}
	}

	@Override
	public BeforeData addBefore(String fsNodeCode, TreeBuildType treeBuildType, String shopGuid) throws ServiceException {
		ScmTbseqno model = new ScmTbseqno();
		model.setFsShopGUID(shopGuid);
		model.setFsCls(treeBuildType.name());
		ScmTbfinderlist tbfinderlist = new ScmTbfinderlist();
		tbfinderlist.setFsShopGUID(shopGuid);
		tbfinderlist.setFsFinderId(treeBuildType.name());
		ScmTbfinderlist result = tbfinderlistService.select(tbfinderlist);
		String auto = "0";
		if (null != result && StringUtils.isNotBlank(result.getFsData())) {
			auto = result.getFsData();
		}
		boolean isAuto = false;
		if ("1".equals(auto)) {
			isAuto = true;
		}
		if (StringUtils.isNotBlank(fsNodeCode)) {
			ScmTbtreebuildParam param = new ScmTbtreebuildParam();
			param.setFsShopGUID(shopGuid);
			param.setFsNodeCode(fsNodeCode);
			param.setFsTreeTypeId(treeBuildType.name());
			selectByKey(param);
			return BeforeData.build(isAuto, null, selectByKey(param));
		}
		if (isAuto) {
			return BeforeData.build(isAuto, seqNoService.selectSeqNo(model), null);
		} else {
			return BeforeData.build(isAuto, null, null);
		}
	}

	@Override
	public List<ScmTbtreebuild> getParentNodeCodeAndNodeCodeInfo(String fsShopGUID, String fsTreeTypeId,
																 String fsNodeCode) throws ServiceException {
		List<ScmTbtreebuild> scmTbtreebuildList = scmTbtreebuildMapper.getParentNodeCodeAndNodeCodeInfo(fsShopGUID, fsTreeTypeId, fsNodeCode);
		return scmTbtreebuildList;
	}

	@Override
	public List<ScmTbtreebuild> getAllByTypeAndShopGuid(String fsShopGUID, String fsTreeTypeId) throws ServiceException {
		Example example = new Example(ScmTbtreebuild.class);
		example.createCriteria().andEqualTo("fsShopGUID", fsShopGUID).andEqualTo("fsTreeTypeId", fsTreeTypeId);
		return scmTbtreebuildMapper.selectByExample(example);
	}

	@Override
	public Map<String, ScmTbtreebuild> getAllByTypeAndShopGuidToMap(String fsShopGUID, String fsTreeTypeId) throws ServiceException {
		Example example = new Example(ScmTbtreebuild.class);
		example.createCriteria().andEqualTo("fsShopGUID", fsShopGUID).andEqualTo("fsTreeTypeId", fsTreeTypeId);
		List<ScmTbtreebuild> list = scmTbtreebuildMapper.selectByExample(example);
		Map<String, ScmTbtreebuild> map = Maps.newHashMap();
		list.stream().forEach(e -> {
			map.put(e.getFsNodeCode(), e);
		});
		return map;
	}

	@Override
	public List<ScmTbtreebuild> findFullCode(String shopGuid, String fullCode, String fsTreeTypeId) throws ServiceException {
		Example example = new Example(ScmTbtreebuild.class);
		example.createCriteria().andEqualTo("fsShopGUID", shopGuid).andEqualTo("fsTreeTypeId", fsTreeTypeId).andLike("fsNodeFullCode", "%".concat(fullCode).concat("%"));
		return scmTbtreebuildMapper.selectByExample(example);
	}

	@Override
	public int classSorting(ScmTbtreebuildParam model) {
		if (StringUtils.isBlank(model.getFsTreeTypeId()) || StringUtils.isBlank(model.getFsTreeTypeId()) || StringUtils.isBlank(model.getFsNodeCode())) {
			return 0;
		}
		Example example = new Example(ScmTbtreebuild.class);
		example.createCriteria().andEqualTo("fsShopGUID", model.getFsShopGUID()).andEqualTo("fsTreeTypeId", model.getFsTreeTypeId()).andEqualTo("fsNodeCode", model.getFsNodeCode());
		ScmTbtreebuild tbtreebuild = new ScmTbtreebuild();
		BeanUtils.copyProperties(model, tbtreebuild);
		int i = scmTbtreebuildMapper.updateByExampleSelective(tbtreebuild, example);
		return i;
	}
}
